package com.zhukunri.sp03.service;

import com.fasterxml.jackson.core.type.TypeReference;
import com.zhukunri.sp01.domain.User;
import com.zhukunri.sp01.service.UserService;
import com.zhukunri.sp01.web.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import java.util.List;


@RefreshScope//自动刷新，从配置文件中获取信息，重写加入业务对象
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    //从配置文件中，注入数据
    @Value("${sp.user-service.users}")
    private String userJson;

    //根据用户的id获取用户信息
    @Override
    public User getUser(Integer id) {
        log.info("用户的id："+id);
        //userJson转成对象List<User>  new TypeReference：设置转成的数据类型为List<User>
        List<User> users = JsonUtil.from(userJson, new TypeReference<List<User>>() {
        });

        //根据用户的id，从数据中查询user对象
        for (User user : users) {
            if (id == user.getId()){
                return user;
            }
        }
        return new User(id,"用户名："+id,"密码："+id);
    }

    //给用户添加积分
    @Override
    public void addScore(Integer id, Integer score) {
        log.info("增加用户积分，id="+id+"，score="+score);
    }
}
